#define  _CRT_SECURE_NO_WARNINGS
#include "DList.h"

ListNode* ListCreate()
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (!node)
	{
		perror("ListCreate::malloc");
		return NULL;
	}
	node->_data = 0;
	node->_next = node->_prev = node;
	return node;
}

void ListDestroy(ListNode* pHead)
{
	if (pHead == NULL)return;
	ListNode* cur = pHead->_next;
	while (cur!=pHead)
	{
		ListNode* next = cur->_next;
		free(cur);
		cur = next;
	}
	free(cur);
}

void ListPrint(ListNode* pHead)
{
	assert(pHead);
	ListNode* cur = pHead->_next;
	printf("Guard->");
	while (cur!=pHead)
	{
		printf("%d->", cur->_data);
		cur = cur->_next;
	}
	printf("Guard\n");
}

ListNode* BuyListNode(LTDataType x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	if (!node)
	{
		perror("BuyListNode::malloc");
		return NULL;
	}
	node->_data = x;
	node->_next = node->_prev = node;
	return node;
}

void ListPushBack(ListNode* pHead, LTDataType x)
{
	ListNode* newnode = BuyListNode(x);
	newnode->_next = pHead;
	newnode->_prev = pHead->_prev;
	pHead->_prev = newnode;
	newnode->_prev->_next = newnode;
}

void ListPopBack(ListNode* pHead)
{
	assert(pHead);
	assert(pHead->_next != pHead);
	pHead->_prev = pHead->_prev->_prev;
	free(pHead->_prev->_next);
	pHead->_prev->_next = pHead;
}


void ListPushFront(ListNode* pHead, LTDataType x)
{
	ListNode* newnode = BuyListNode(x);
	newnode->_prev = pHead;
	newnode->_next = pHead->_next;
	pHead->_next = newnode;
	newnode->_next->_prev = newnode;
}

void ListPopFront(ListNode* pHead)
{
	assert(pHead);
	assert(pHead->_next != pHead);
	pHead->_next = pHead->_next->_next;
	free(pHead->_next->_prev);
	pHead->_next->_prev = pHead;
}

ListNode* ListFind(ListNode* pHead, LTDataType x)
{
	ListNode* cur = pHead->_next;
	while (cur != pHead)
	{
		if (cur->_data == x)return cur;
		cur = cur->_next;
	}
	return NULL;
}

void ListInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListPushFront(pos, x);
}

void ListErase(ListNode* pos)
{
	assert(pos);
	assert(pos->_next != pos);
	ListPopBack(pos->_next);
}